﻿using DevExpress.XtraEditors;
using HslCommunicationDemo;
using Microsoft.AspNet.SignalR.Client;
using SmartFrame_DataCollect.Forms;
using SmartFrame_DataCollect.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Threading;

namespace SmartFrame_DataCollect
{
    public partial class Tasks : BaseModule
    {
        public List<DeviceConfig> listAllDeviceConfig = new List<DeviceConfig>();
        public List<Protocol> listProtocal = new List<Protocol>();

        public Tasks()
        {
            InitializeComponent();
            var editOper1 = new DevExpress.XtraEditors.Controls.EditorButton()
            {
                Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph,
                Caption = "开始",
                IsLeft = true,

            };
            editOper1.ImageOptions.Image = global::SmartFrame_DataCollect.Properties.Resources.Play_16x16;
            editOper1.ImageOptions.ImageToTextAlignment = DevExpress.XtraEditors.ImageAlignToText.LeftCenter;
            editOper1.Width = 50;
            editOper1.Click += EditOper1_Click;


            var editOper2 = new DevExpress.XtraEditors.Controls.EditorButton()
            {
                Kind = DevExpress.XtraEditors.Controls.ButtonPredefines.Glyph,
                Caption = "停止",
                IsLeft = true,

            };
            editOper2.ImageOptions.Image = global::SmartFrame_DataCollect.Properties.Resources.Stop_16x16;
            editOper2.ImageOptions.ImageToTextAlignment = DevExpress.XtraEditors.ImageAlignToText.LeftCenter;

            editOper2.Width = 50;
            editOper2.Click += EditOper2_Click;


            this.repositoryItemButtonEdit1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
                editOper2,
                editOper1
             });
            
            InitDeviceAllList();
            InitConnection(false);
            InitServerConnection();
        }
        /// <summary>
        /// 初始化设备所有清单，及通讯模块
        /// </summary>
        public void InitDeviceAllList()
        {
            string cjRange = ConfigurationManager.AppSettings["CJRange"];
            if(cjRange!="")
            {
                cjRange = " and bae.EquipmentID in (select EquipID from " + DataBaseHelper.CJDBName + @".[dbo].[Ba_EquipConfig] where  "+ cjRange + " ) ";
            }
            else
            {
                cjRange = " and 1=1 ";
            }

            string deviceNo = editEquipNo.EditValue == null ? "" : editEquipNo.EditValue.ToString();
            string sql = @"SELECT bae.*,baetype.EquipmentTypeName FROM Ba_EquipmentType as baetype LEFT JOIN 
                           Ba_Equipment as bae ON baetype.EquipmentTypeID = bae.UpID WHERE IsCJ = 1 "+ cjRange +@" and EquipmentCode like '%" + deviceNo + @"%'
                           select * from " + DataBaseHelper.CJDBName + @".[dbo].[Ba_EquipConfig]
                           select * from " + DataBaseHelper.CJDBName + @".[dbo].[Ba_EquipVarConfig]
                           select * from " + DataBaseHelper.CJDBName + @".[dbo].[Ba_DBConfig]
                           select * from " + DataBaseHelper.CJDBName + @".[dbo].[Ba_EquipJSONConfig]
                           select * from " + DataBaseHelper.CJDBName + @".[dbo].[Ba_EquipWebAPIConfig]
                           select * from " + DataBaseHelper.CJDBName + @".[dbo].[Ba_EquipWebAPIDetailConfig]";
            DataSet dsDevice = DbHelperSQL.Query(sql);
            listAllDeviceConfig = new List<DeviceConfig>();
            if (dsDevice!=null && dsDevice.Tables.Count>0)
            {
                foreach (DataRow drDevice in dsDevice.Tables[0].Rows)
                {
                    DeviceConfig deviceConfig = new DeviceConfig();
                    deviceConfig.DeviceID = int.Parse(drDevice["EquipmentID"].ToString());
                    deviceConfig.DeviceNo = drDevice["EquipmentCode"].ToString();
                    deviceConfig.IsRunning = false;

                    var equipConfigObj = dsDevice.Tables[1].AsEnumerable().Where(x => x["EquipID"].ToString() == deviceConfig.DeviceID.ToString()).FirstOrDefault();
                    if(equipConfigObj !=null)
                    {
                        deviceConfig.ProtocalConfig = equipConfigObj["ProtocolConfig"].ToString();
                        deviceConfig.SaveDataTime = equipConfigObj["SaveDataTime"].ToString();
                        deviceConfig.RunRangeTime = equipConfigObj["RunRangeTime"].ToString();
                        deviceConfig.DataBaseConfig = equipConfigObj["DataBaseConfig"].ToString();
                        deviceConfig.VarList = new List<DeviceVarConfig>();
                        var equipVarList = dsDevice.Tables[2].AsEnumerable().Where(x => x["EquipID"].ToString() == deviceConfig.DeviceID.ToString()).ToList();
                        foreach (DataRow varRow in equipVarList)
                        {
                            DeviceVarConfig varConfig = new DeviceVarConfig();
                            varConfig.VarType = varRow["VarType"].ToString();
                            varConfig.VarRequency = int.Parse(varRow["VarRequency"].ToString());
                            varConfig.VarName = varRow["VarName"].ToString();
                            varConfig.VarSpecial = varRow["VarSpecial"].ToString();
                            varConfig.VarPath = varRow["VarPath"].ToString();
                            deviceConfig.VarList.Add(varConfig);
                        }
                        deviceConfig.VarJSONList = new List<DeviceJSONConfig>();
                        var equipJSONList = dsDevice.Tables[4].AsEnumerable().Where(x => x["EquipID"].ToString() == deviceConfig.DeviceID.ToString()).ToList();
                        foreach (DataRow jsonRow in equipJSONList)
                        {
                            DeviceJSONConfig deviceJSONConfig = new DeviceJSONConfig();
                            deviceJSONConfig.EquipJSONConfigID = jsonRow["EquipJSONConfigID"].ToString();
                            deviceJSONConfig.NodeName = jsonRow["NodeName"].ToString();
                            deviceJSONConfig.NodeType = jsonRow["NodeType"].ToString();
                            deviceJSONConfig.ParentID = jsonRow["ParentID"].ToString();
                            deviceConfig.VarJSONList.Add(deviceJSONConfig);
                        }
                        deviceConfig.CollectWebAPIList = new List<CollectWebAPIConfig>();
                        var webAPIList = dsDevice.Tables[5].AsEnumerable().Where(x => x["EquipID"].ToString() == deviceConfig.DeviceID.ToString()).ToList();
                        foreach (DataRow webapiRow in webAPIList)
                        {
                            CollectWebAPIConfig collectWebAPIConfig = new CollectWebAPIConfig();
                            collectWebAPIConfig.EquipID = int.Parse(webapiRow["EquipID"].ToString());
                            collectWebAPIConfig.EquipWebAPIConfigID = int.Parse(webapiRow["EquipWebAPIConfigID"].ToString());
                            collectWebAPIConfig.ParamUrl = webapiRow["ParamUrl"].ToString();
                            collectWebAPIConfig.listDetailConfig = new List<CollectWebAPIDetailConfig>();
                            var webAPIDetailList = dsDevice.Tables[6].AsEnumerable().Where(x => x["EquipWebAPIConfigID"].ToString() == collectWebAPIConfig.EquipWebAPIConfigID.ToString()).ToList();
                            foreach (DataRow webapiDetailRow in webAPIDetailList)
                            {
                                CollectWebAPIDetailConfig collectDetailWebAPIConfig = new CollectWebAPIDetailConfig();
                                collectDetailWebAPIConfig.EquipWebAPIConfigDeID = webapiDetailRow["EquipWebAPIConfigDeID"].ToString();
                                collectDetailWebAPIConfig.EquipWebAPIConfigID = int.Parse(webapiDetailRow["EquipWebAPIConfigID"].ToString());
                                collectDetailWebAPIConfig.NodeName = webapiDetailRow["NodeName"].ToString();
                                collectDetailWebAPIConfig.NodeType = webapiDetailRow["NodeType"].ToString();
                                collectDetailWebAPIConfig.ParentID = webapiDetailRow["ParentID"].ToString();
                                collectWebAPIConfig.listDetailConfig.Add(collectDetailWebAPIConfig);
                            }
                            deviceConfig.CollectWebAPIList.Add(collectWebAPIConfig);
                        }
                    }
                    listAllDeviceConfig.Add(deviceConfig);
                }
            }
            listProtocal = new List<Protocol>();
            if (dsDevice!=null && dsDevice.Tables.Count>1)
            {
                foreach (DataRow drProtocal in dsDevice.Tables[3].Rows)
                {
                    Protocol protocol = new Protocol();
                    protocol.ConnStr = drProtocal["ConnStr"].ToString();
                    protocol.DBConfigType = drProtocal["DBConfigType"].ToString();
                    protocol.DBNum = drProtocal["DBNum"].ToString() == "" ? 0 : int.Parse(drProtocal["DBNum"].ToString());
                    if (drProtocal["IsSubTable"].ToString() == "")
                    {
                        protocol.IsSubTable = null;
                    }
                    else
                    {
                        protocol.IsSubTable = drProtocal["IsSubTable"].ToString() == "True" ? 1 : 0;
                    }
                    protocol.SubTableType = drProtocal["SubTableType"].ToString();
                    listProtocal.Add(protocol);
                }
            }
            RefreshGridView();
        }

        private void RefreshGridView()
        {
            gridDeviceList.DataSource = listAllDeviceConfig;
        }




        #region signalr通讯
        HubConnection connection;
        IHubProxy dataCollectHub { get; set; }
        public bool IsConnect;

        HubConnection serviceHubConnection;
        IHubProxy serverHub { get; set; }


        public void InitConnection(bool isInitConfig)
        {
            //10008作为本地signalR通讯端口
            connection = new HubConnection("http://127.0.0.1:10008/signalr");
            dataCollectHub = connection.CreateHubProxy("DataCollectHub");
            //开始连接
            connection.Start().ContinueWith(t =>
            {
                if (!t.IsFaulted)
                {
                    IsConnect = true;
                    //初始化配置
                    if(isInitConfig)
                    {
                        editEquipNo.EditValue = "";
                        InitDeviceAllList();
                        dataCollectHub.Invoke("InitDeviceCollectConfig", listAllDeviceConfig.ToJSON(), listProtocal.ToJSON(), DataBaseHelper.ServiceIP);
                        string content = listAllDeviceConfig.ToJSON() + "^" + listProtocal.ToJSON() + "^" + DataBaseHelper.ServiceIP;
                        RecordDeviceConfig(content);
                    }
                }
                else
                {
                    IsConnect = false;
                    XtraMessageBox.Show("通讯连接异常，请检查是否已开启采集服务", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            });
            dataCollectHub.On("OnGetAllDeviceStatus", (string listDeviceConfigStr) =>
            {
                if(!ckOnline.Checked)
                {
                    try
                    {
                        List<DeviceConfig> listDeviceConfig = listDeviceConfigStr.FromJSON<List<DeviceConfig>>();
                        //MessageBox.Show(listDeviceConfigStr);
                        listAllDeviceConfig = listDeviceConfig;
                    }
                    catch (Exception e)
                    {

                    }
                }
            });
        }


        public void InitServerConnection()
        {
            serviceHubConnection = new HubConnection("http://" + DataBaseHelper.ServiceIP + "/signalr");
            serverHub = serviceHubConnection.CreateHubProxy("CJDataHub");
            //开始连接
            serviceHubConnection.Start().ContinueWith(t =>
            {
                if (!t.IsFaulted)
                {
                    if(ckOnline.Checked)
                    {
                        
                    }
                }
                else
                {
                    XtraMessageBox.Show("服务端通讯连接异常，请检查是否已开启采集服务", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            });

            serverHub.On("onGetDeviceStatus", (string listDeviceConfigStr) =>
            {
                if (ckOnline.Checked)
                {
                    try
                    {
                        List<DeviceConfig> listDeviceConfig = listDeviceConfigStr.FromJSON<List<DeviceConfig>>();
                        //MessageBox.Show(listDeviceConfigStr);
                        listAllDeviceConfig = listDeviceConfig;
                    }
                    catch (Exception e)
                    {

                    }
                }
            });
        }


        #endregion

        private void btnService_Click(object sender, EventArgs e)
        {
            frmService frmSrv = new frmService(this);
            frmSrv.Show();
        }

        private void btnAllStart_Click(object sender, EventArgs e)
        {
            dataCollectHub.Invoke("PlayAllDeviceCollect");
            //var deviceConfigList = gridView1.DataSource as List<DeviceConfig>;
            ////逐条开启服务
            //Thread threadTask = new Thread(() =>
            //{
            //    foreach (var item in deviceConfigList)
            //    {
            //        dataCollectHub.Invoke("PlaySingleDeviceCollect", item.DeviceID.ToString());
            //        Thread.Sleep(2000);
            //    }
            //});
            //threadTask.Start();


            
            XtraMessageBox.Show("全部设备已开启,请耐心等待设备运行状态","提示",MessageBoxButtons.OK);
        }

        private void btnAllStop_Click(object sender, EventArgs e)
        {
            dataCollectHub.Invoke("StopAllDeviceCollect");
            XtraMessageBox.Show("全部设备已停止,请耐心等待设备运行状态", "提示", MessageBoxButtons.OK);
        }

        protected void EditOper1_Click(object sender,EventArgs e)
        {
            //选中行数据
            //var focusedRow = gridView1.GetFocusedDataRow();
            try
            {
                var selectRows = gridView1.GetSelectedRows();
                if (selectRows.Count() > 0)
                {
                    var deviceConfigList = gridView1.DataSource as List<DeviceConfig>;

                    dataCollectHub.Invoke("PlaySingleDeviceCollect", deviceConfigList[selectRows[0]].DeviceID.ToString());
                    XtraMessageBox.Show("设备" + deviceConfigList[selectRows[0]].DeviceNo.ToString() + "已开启,请耐心等待设备运行状态", "提示", MessageBoxButtons.OK);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.ToString());
            }
        }

        protected void EditOper2_Click(object sender, EventArgs e)
        {
            try
            {
                //选中行数据
                var selectRows = gridView1.GetSelectedRows();
                if (selectRows.Count() > 0)
                {
                    var deviceConfigList = gridView1.DataSource as List<DeviceConfig>;

                    dataCollectHub.Invoke("StopSingleDeviceCollect", deviceConfigList[selectRows[0]].DeviceID.ToString());
                    XtraMessageBox.Show("设备" + deviceConfigList[selectRows[0]].DeviceNo.ToString() + "已停止,请耐心等待设备运行状态", "提示", MessageBoxButtons.OK);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.ToString());
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            InitDeviceAllList();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //每隔5秒刷新下页面数据
            RefreshGridView();
        }

        private void RecordDeviceConfig(string deviceConfig)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"\DeviceConfigData.ini";
            File.WriteAllText(path, deviceConfig);
        }

    }
}
